package com.fsserver.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fsserver.common.constants.PaymentConstants;
import com.fsserver.core.dto.PaymentOrderDTO;
import com.fsserver.core.entity.PaymentOrder;
import com.fsserver.core.mapper.PaymentOrderMapper;
import com.fsserver.core.service.PaymentOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 支付订单服务实现类
 * Payment Order Service Implementation
 *
 * @author fsserver
 */
@Slf4j
@Service
public class PaymentOrderServiceImpl extends BaseServiceImpl<PaymentOrderMapper, PaymentOrder> implements PaymentOrderService {

    /**
     * 创建支付订单
     * Create payment order
     *
     * @param paymentOrderDTO 支付订单DTO
     * @return 支付订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PaymentOrder createOrder(PaymentOrderDTO paymentOrderDTO) {
        log.info("创建支付订单: {}", paymentOrderDTO);
        
        // 创建支付订单
        PaymentOrder paymentOrder = new PaymentOrder();
        BeanUtils.copyProperties(paymentOrderDTO, paymentOrder);
        
        // 设置订单号
        paymentOrder.setOrderNo(generateOrderNo());
        
        // 设置订单状态
        paymentOrder.setStatus(PaymentConstants.PaymentStatus.INIT);
        
        // 设置过期时间
        if (paymentOrderDTO.getExpirationMinutes() != null && paymentOrderDTO.getExpirationMinutes() > 0) {
            Date expirationTime = new Date(System.currentTimeMillis() + paymentOrderDTO.getExpirationMinutes() * 60 * 1000L);
            paymentOrder.setExpirationTime(expirationTime);
        }
        
        // 保存支付订单
        save(paymentOrder);
        
        log.info("支付订单创建成功: {}", paymentOrder);
        return paymentOrder;
    }

    /**
     * 根据ID获取支付订单
     * Get payment order by ID
     *
     * @param id 支付订单ID
     * @return 支付订单
     */
    @Override
    public PaymentOrder getOrderById(Long id) {
        return getById(id);
    }

    /**
     * 根据订单号获取支付订单
     * Get payment order by order number
     *
     * @param orderNo 订单号
     * @return 支付订单
     */
    @Override
    public PaymentOrder getOrderByOrderNo(String orderNo) {
        return getOne(new LambdaQueryWrapper<PaymentOrder>()
                .eq(PaymentOrder::getOrderNo, orderNo));
    }

    /**
     * 根据业务订单号获取支付订单
     * Get payment order by business order number
     *
     * @param businessOrderNo 业务订单号
     * @return 支付订单
     */
    @Override
    public PaymentOrder getOrderByBusinessOrderNo(String businessOrderNo) {
        return getOne(new LambdaQueryWrapper<PaymentOrder>()
                .eq(PaymentOrder::getBusinessOrderNo, businessOrderNo));
    }

    /**
     * 根据状态查询支付订单列表
     * List payment orders by status
     *
     * @param status 支付订单状态
     * @return 支付订单列表
     */
    @Override
    public List<PaymentOrder> listOrdersByStatus(String status) {
        return list(new LambdaQueryWrapper<PaymentOrder>()
                .eq(PaymentOrder::getStatus, status)
                .orderByDesc(PaymentOrder::getCreateTime));
    }

    /**
     * 根据用户ID查询支付订单列表
     * List payment orders by user ID
     *
     * @param userId 用户ID
     * @return 支付订单列表
     */
    @Override
    public List<PaymentOrder> listOrdersByUserId(Long userId) {
        return list(new LambdaQueryWrapper<PaymentOrder>()
                .eq(PaymentOrder::getUserId, userId)
                .orderByDesc(PaymentOrder::getCreateTime));
    }

    /**
     * 关闭支付订单
     * Close payment order
     *
     * @param orderNo 订单号
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean closeOrder(String orderNo) {
        log.info("关闭支付订单: {}", orderNo);
        
        // 获取支付订单
        PaymentOrder paymentOrder = getOrderByOrderNo(orderNo);
        if (paymentOrder == null) {
            log.error("支付订单不存在: {}", orderNo);
            return false;
        }
        
        // 检查订单状态
        if (!PaymentConstants.PaymentStatus.INIT.equals(paymentOrder.getStatus()) && 
            !PaymentConstants.PaymentStatus.PROCESSING.equals(paymentOrder.getStatus())) {
            log.error("支付订单状态不允许关闭: {}, {}", orderNo, paymentOrder.getStatus());
            return false;
        }
        
        // 更新订单状态
        boolean result = update(new LambdaUpdateWrapper<PaymentOrder>()
                .eq(PaymentOrder::getOrderNo, orderNo)
                .set(PaymentOrder::getStatus, PaymentConstants.PaymentStatus.CLOSED)
                .set(PaymentOrder::getCloseTime, new Date()));
        
        log.info("支付订单关闭结果: {}, {}", orderNo, result);
        return result;
    }

    /**
     * 更新支付订单状态
     * Update payment order status
     *
     * @param orderNo 订单号
     * @param status  支付订单状态
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderStatus(String orderNo, String status) {
        log.info("更新支付订单状态: {}, {}", orderNo, status);
        
        // 获取支付订单
        PaymentOrder paymentOrder = getOrderByOrderNo(orderNo);
        if (paymentOrder == null) {
            log.error("支付订单不存在: {}", orderNo);
            return false;
        }
        
        // 更新订单状态
        LambdaUpdateWrapper<PaymentOrder> updateWrapper = new LambdaUpdateWrapper<PaymentOrder>()
                .eq(PaymentOrder::getOrderNo, orderNo)
                .set(PaymentOrder::getStatus, status);
        
        // 如果状态为成功，设置支付时间
        if (PaymentConstants.PaymentStatus.SUCCESS.equals(status)) {
            updateWrapper.set(PaymentOrder::getPaymentTime, new Date());
        }
        
        // 如果状态为关闭，设置关闭时间
        if (PaymentConstants.PaymentStatus.CLOSED.equals(status)) {
            updateWrapper.set(PaymentOrder::getCloseTime, new Date());
        }
        
        boolean result = update(updateWrapper);
        
        log.info("支付订单状态更新结果: {}, {}, {}", orderNo, status, result);
        return result;
    }
    
    /**
     * 生成订单号
     * Generate order number
     *
     * @return 订单号
     */
    private String generateOrderNo() {
        // 生成订单号：时间戳 + 6位随机数
        return System.currentTimeMillis() + String.format("%06d", (int) (Math.random() * 1000000));
    }
} 